<template>
  <div class="min-h-screen py-8 px-4 sm:px-6 lg:px-8">
    <div class="max-w-4xl mx-auto">
      <!-- 页面标题 -->
      <div class="text-center mb-12">
        <h1 class="text-4xl font-bold mb-4 tech-text">屏幕捕捉 API</h1>
        <p class="text-gray-300 text-lg">
          使用 Screen Capture API 录制屏幕内容，支持整个屏幕、应用窗口或浏览器标签页
        </p>
      </div>

      <!-- 演示区域 -->
      <div class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">实时演示</h2>
        
        <!-- 视频预览 -->
        <div class="mb-6">
          <video
            ref="videoElement"
            class="w-full max-w-2xl mx-auto rounded-lg bg-gray-900 border border-gray-700"
            autoplay
            muted
            playsinline
          ></video>
        </div>

        <!-- 控制按钮 -->
        <div class="flex flex-wrap gap-4 justify-center mb-6">
          <button
            @click="startCapture"
            :disabled="isCapturing"
            class="tech-button disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <i class="i-carbon-screen mr-2"></i>
            {{ isCapturing ? '正在捕获...' : '开始屏幕捕获' }}
          </button>
          
          <button
            @click="stopCapture"
            :disabled="!isCapturing"
            class="bg-red-600 hover:bg-red-700 text-white px-6 py-3 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <i class="i-carbon-stop mr-2"></i>
            停止捕获
          </button>
          
          <button
            @click="startRecording"
            :disabled="!isCapturing || isRecording"
            class="bg-green-600 hover:bg-green-700 text-white px-6 py-3 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <i class="i-carbon-video mr-2"></i>
            {{ isRecording ? '录制中...' : '开始录制' }}
          </button>
          
          <button
            @click="stopRecording"
            :disabled="!isRecording"
            class="bg-orange-600 hover:bg-orange-700 text-white px-6 py-3 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <i class="i-carbon-stop-filled mr-2"></i>
            停止录制
          </button>
        </div>

        <!-- 状态信息 -->
        <div class="text-center text-gray-400">
          <p v-if="!isCapturing && !error">点击"开始屏幕捕获"来选择要捕获的屏幕或窗口</p>
          <p v-if="isCapturing" class="text-tech-accent">✓ 屏幕捕获已激活</p>
          <p v-if="isRecording" class="text-green-400">🔴 正在录制中... 时长: {{ recordingTime }}s</p>
          <p v-if="error" class="text-red-400">❌ {{ error }}</p>
        </div>
      </div>

      <!-- 录制结果 -->
      <div v-if="recordedBlobs.length > 0" class="tech-card mb-8">
        <h3 class="text-xl font-semibold mb-4 text-white">录制结果</h3>
        <div class="space-y-4">
          <div
            v-for="(blob, index) in recordedBlobs"
            :key="index"
            class="flex items-center justify-between p-4 bg-gray-800 rounded-lg"
          >
            <div>
              <p class="text-white font-medium">录制 {{ index + 1 }}</p>
              <p class="text-gray-400 text-sm">大小: {{ formatFileSize(blob.size) }}</p>
            </div>
            <div class="flex gap-2">
              <button
                @click="playRecording(blob)"
                class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded transition-colors"
              >
                <i class="i-carbon-play mr-1"></i>
                播放
              </button>
              <button
                @click="downloadRecording(blob, index)"
                class="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded transition-colors"
              >
                <i class="i-carbon-download mr-1"></i>
                下载
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- API 信息 -->
      <div class="tech-card">
        <h3 class="text-xl font-semibold mb-4 text-white">API 信息</h3>
        <div class="space-y-4 text-gray-300">
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">浏览器支持</h4>
            <p>Chrome 72+, Firefox 66+, Safari 13+</p>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">主要方法</h4>
            <ul class="list-disc list-inside space-y-1">
              <li><code class="bg-gray-800 px-2 py-1 rounded">navigator.mediaDevices.getDisplayMedia()</code> - 获取屏幕媒体流</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">MediaRecorder</code> - 录制媒体流</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">stream.getTracks()</code> - 获取媒体轨道</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">使用场景</h4>
            <ul class="list-disc list-inside space-y-1">
              <li>在线教育和培训录制</li>
              <li>软件演示和教程制作</li>
              <li>远程协作和屏幕共享</li>
              <li>技术支持和问题诊断</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onUnmounted } from 'vue'

// 响应式状态
const videoElement = ref<HTMLVideoElement>()
const isCapturing = ref(false)
const isRecording = ref(false)
const error = ref('')
const recordingTime = ref(0)
const recordedBlobs = ref<Blob[]>([])

// 媒体相关
let mediaStream: MediaStream | null = null
let mediaRecorder: MediaRecorder | null = null
let recordingTimer: ReturnType<typeof setInterval> | null = null
let chunks: Blob[] = []

// 开始屏幕捕获
const startCapture = async () => {
  try {
    error.value = ''
    
    // 检查浏览器支持
    if (!navigator.mediaDevices || !navigator.mediaDevices.getDisplayMedia) {
      throw new Error('您的浏览器不支持屏幕捕获功能')
    }

    // 获取屏幕媒体流
    mediaStream = await navigator.mediaDevices.getDisplayMedia({
      video: {
        width: { ideal: 1920 },
        height: { ideal: 1080 },
        frameRate: { ideal: 30 }
      },
      audio: true
    })

    // 设置视频元素
    if (videoElement.value) {
      videoElement.value.srcObject = mediaStream
    }

    isCapturing.value = true

    // 监听流结束事件
    mediaStream.getVideoTracks()[0].addEventListener('ended', () => {
      stopCapture()
    })

  } catch (err) {
    console.error('屏幕捕获失败:', err)
    error.value = err instanceof Error ? err.message : '屏幕捕获失败'
  }
}

// 停止屏幕捕获
const stopCapture = () => {
  if (mediaStream) {
    mediaStream.getTracks().forEach(track => track.stop())
    mediaStream = null
  }
  
  if (videoElement.value) {
    videoElement.value.srcObject = null
  }
  
  isCapturing.value = false
  
  if (isRecording.value) {
    stopRecording()
  }
}

// 开始录制
const startRecording = () => {
  if (!mediaStream) return

  try {
    chunks = []
    mediaRecorder = new MediaRecorder(mediaStream, {
      mimeType: 'video/webm;codecs=vp9'
    })

    mediaRecorder.ondataavailable = (event) => {
      if (event.data.size > 0) {
        chunks.push(event.data)
      }
    }

    mediaRecorder.onstop = () => {
      const blob = new Blob(chunks, { type: 'video/webm' })
      recordedBlobs.value.push(blob)
      chunks = []
    }

    mediaRecorder.start(1000) // 每秒收集一次数据
    isRecording.value = true
    recordingTime.value = 0

    // 开始计时
    recordingTimer = setInterval(() => {
      recordingTime.value++
    }, 1000)

  } catch (err) {
    console.error('录制失败:', err)
    error.value = '录制失败'
  }
}

// 停止录制
const stopRecording = () => {
  if (mediaRecorder && mediaRecorder.state !== 'inactive') {
    mediaRecorder.stop()
  }
  
  isRecording.value = false
  
  if (recordingTimer) {
    clearInterval(recordingTimer)
    recordingTimer = null
  }
}

// 播放录制内容
const playRecording = (blob: Blob) => {
  const url = URL.createObjectURL(blob)
  const video = document.createElement('video')
  video.src = url
  video.controls = true
  video.style.maxWidth = '100%'
  
  // 创建模态框显示视频
  const modal = document.createElement('div')
  modal.className = 'fixed inset-0 bg-black bg-opacity-75 flex items-center justify-center z-50 p-4'
  modal.onclick = () => {
    document.body.removeChild(modal)
    URL.revokeObjectURL(url)
  }
  
  const container = document.createElement('div')
  container.className = 'bg-gray-900 p-4 rounded-lg max-w-4xl w-full'
  container.onclick = (e) => e.stopPropagation()
  
  container.appendChild(video)
  modal.appendChild(container)
  document.body.appendChild(modal)
}

// 下载录制内容
const downloadRecording = (blob: Blob, index: number) => {
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `screen-recording-${index + 1}-${Date.now()}.webm`
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
}

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 清理资源
onUnmounted(() => {
  stopCapture()
  if (recordingTimer) {
    clearInterval(recordingTimer)
  }
})
</script>
